from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
from routers import (
    settings_router, 
    agent_router, 
    assessment_plan_router, 
    compliance_item_router, 
    relation_router, 
    attachment_router,
    compliance_template_router,
    issue_router,
    remediation_router,
    proofmapper_router
)
# 文档管理路由
from routers.document import document_category_router, document_tag_router, personal_document_router, document_relation_router
from log import configure_logging, log_error, log_info
from db.session import engine, get_db
from db.base import Base
from crud.settings import get_settings
from config import settings as app_settings
from db import modify as db_modify

# 创建数据库表（如果不存在）
async def create_tables():
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动时执行
    try:
        # 创建数据库表
        await create_tables()
        
        # 手动应用数据库修改
        log_info("开始应用手动数据库修改...")
        await db_modify.apply(engine)
        log_info("手动数据库修改应用完成")
        
        # 从数据库加载设置并初始化系统数据
        async for db in get_db():
            try:
                # 查询设置
                db_settings = await get_settings(db)
                
                # 如果有设置记录，更新全局配置
                if db_settings and len(db_settings) > 0:
                    first_setting = db_settings[0]  # 获取第一条设置记录
                    
                    # 更新全局配置
                    app_settings.OPENAI_API_KEY = first_setting.api_key
                    app_settings.OPENAI_BASE_URL = first_setting.api_url
                    app_settings.OPENAI_MODEL = first_setting.model
                    
                    log_info("已从数据库加载OpenAI配置")
                else:
                    log_info("数据库中没有找到设置记录，使用默认配置")
                
                # 初始化系统预设分类
                try:
                    from core.document.document_category import initialize_system_categories
                    await initialize_system_categories(db)
                    log_info("系统预设分类初始化完成")
                except Exception as e:
                    log_error(f"初始化系统分类失败：{str(e)}")
                
                break  # 完成设置加载后退出循环
            except Exception as e:
                log_error(f"加载设置异常：{str(e)}")
                break
    except Exception as e:
        log_error(f"应用启动异常：{str(e)}")
    
    yield
    
    # 关闭时执行
    pass

# Create FastAPI app with lifespan context manager
app = FastAPI(
    redirect_slashes=False,
    title="Settings API",
    description="API for managing settings",
    version="0.1.0",
    lifespan=lifespan
)

# Configure CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:8080", "http://127.0.0.1:8080", "http://localhost:3000", "http://127.0.0.1:3000", "http://frontend", "http://frontend:80"],  # 明确指定允许的前端源，包括Docker容器名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Include routers
app.include_router(settings_router)
app.include_router(agent_router)
app.include_router(assessment_plan_router)
app.include_router(compliance_item_router)
app.include_router(relation_router)
app.include_router(attachment_router)
app.include_router(compliance_template_router)
app.include_router(issue_router)
app.include_router(remediation_router)
app.include_router(proofmapper_router)

# 文档管理路由
app.include_router(document_category_router)
app.include_router(document_tag_router)
app.include_router(personal_document_router)
app.include_router(document_relation_router)    
# Disable redirect_slashes for all included routes as well
for route in app.router.routes:
    if hasattr(route, "redirect_slashes"):
        route.redirect_slashes = False

# Configure logging
configure_logging(app)

# Root endpoint
@app.get("/")
async def root():
    return {"message": "Welcome to the Settings & Agent API"}
